<template>
  <div v-loading="loading">
    <table class="table table-bordered vertical-align-middle text-center approve-table">
      <colgroup>
        <col width="16%" />
        <col width="34%" />
        <col width="16%" />
        <col width="34%" />
      </colgroup>
      <tbody>
        <tr>
          <td>反担保方案落实情况</td>
          <td colspan="3" class="text-left" :class="tdClass">
            <div v-if="isView"><div v-html="guaMethodHtml"></div></div>
            <el-input
              v-else
              v-model="approval.gua_method_impl"
              :rows="5"
              type="textarea"
              placeholder="反担保方案落实情况"
            ></el-input>
          </td>
        </tr>
        <tr>
          <td>业务落实情况</td>
          <td colspan="3" class="text-left" :class="tdClass">
            <div v-if="isView" class="text-indent px-4 py-2">
              客户资料已按要求进行收集,相关合同已签署。已缴纳担保费
              <span class="text-decoration px-1">{{ approval.pay_gua_fee || '-' }}</span>
              元
              <span class="text-muted test-sm">（应缴：{{ entrustContract.gua_fee }} 元）</span>
              。 同意办理。
            </div>
            <div v-else class="px-4 mx-4">
              <span>客户资料已按要求进行收集,相关合同已签署。已缴纳担保费</span>
              <el-input
                class="text-decoration"
                placeholder="已缴担保费"
                v-model="approval.pay_gua_fee"
              ></el-input>
              元
              <span class="text-muted">（应缴：{{ entrustContract.gua_fee }} 元）</span>
              。 同意办理。
            </div>
            <div class="d-flex justify-content-between px-4 pt-3">
              <div class="flex-1">项目经理A角： {{ relatedData.res_a_name }}</div>
              <div class="flex-1">项目经理B角： {{ relatedData.res_b_name }}</div>
            </div>
          </td>
        </tr>
        <tr>
          <td>附件资料</td>
          <td colspan="3" class="text-left">
            <div
              class="d-flex justify-content-between align-items-center"
              v-for="(p, key) of enumAttach"
              :key="key"
            >
              <div class="flex-2 pl-2">{{ key }}、{{ p.label }}</div>
              <div class="flex-2">
                <span>{{ +key === 3 ? '当前状态' : '有无附件' }}</span>
                <small>({{ p.must ? '必填' : '非必填' }})</small>
                :
                <small :class="p.status ? 'text-success' : 'text-danger'">
                  {{ p.statusLabel }}
                </small>
              </div>
              <div class="flex-1">
                <el-button type="text" @click="handleAttach(p, false)" v-if="!isView">
                  <i class="fa fa-gavel"></i>
                </el-button>
                <el-button type="text" @click="handleAttach(p, true)">
                  <i class="fa fa-search"></i>
                </el-button>
              </div>
            </div>
          </td>
        </tr>
      </tbody>
    </table>
    <!-- <div class="text-center my-3" v-if="!isView">
      <el-button
        class="btn-long"
        type="primary"
        :loading="submitLoading"
        :disabled="loading"
        @click="handlePass"
      >
        保存
      </el-button>
    </div> -->
    <approve-common
      v-bind="$attrs"
      :view-mode="viewMode"
      :related-data="relatedData"
      :approve-data="approveData"
      :before-save="handlePass"
      @success="handleSuccess"
    ></approve-common>

    <contract-attachment
      :accept="accept"
      :visible.sync="attachVisible"
      @success="refesAttach"
      :view-mode="attachView"
      :query-id="queryId"
      :must="attachMust && !!approvalId"
      :attach-name="attachType"
      :parent-tag="parentTag"
      :attach-data="attachList"
    ></contract-attachment>
  </div>
</template>

<script>
import {
  getLoanData,
  getAttachment,
  // sendNotice,
  updateLoanApproval,
  addLoanApproval,
  getCustomerNotice,
} from '@/credit/views/county/unionProvince/components/loanApproveDeploy/index'
import { getContractData } from '@/credit/views/county/unionProvince/components/contractApproveDeploy/index'
import { updateApprove, addApprove } from '@/credit/mixin/wf'
import ContractAttachment from '@/credit/views/city/self/components/contractRegistr/ContractAttachment'
import { mapGetters } from 'vuex'
import ApproveCommon from '@/credit/views/county/unionProvince/components/loanApproveDeploy/ApproveCommon'
import { formatLine } from '@/common/plugins/tools/format'
export default {
  components: {
    ContractAttachment,
    ApproveCommon,
  },
  props: {
    relatedData: Object,
    viewMode: {
      type: Boolean,
      default: false,
    },
    approveData: {
      type: Object,
      default: () => ({
        editable: false,
        record: [],
      }),
    },
  },
  data() {
    return {
      approval: {},
      submitLoading: false,
      loading: false,
      enumAttach: {},
      parentTag: '放款附件',
      attachName: [
        '签约现场',
        '合同附件',
        '保费缴纳凭证',
        '抵质押登记权证',
        '共同承担责任函（盖章版）',
      ],
      attachVisible: false,
      accept: '',
      attachList: [],
      attachType: '',
      attachMust: false,
      noticeId: '',

      // 合同审批
      contrustApproval: {},
      attachView: false,
    }
  },

  computed: {
    ...mapGetters(['entrustContract', 'user']),
    guaMethodHtml() {
      return formatLine(this.approval.gua_method_impl)
    },
    queryId() {
      return this.relatedData.customer_related_id
    },
    isView() {
      // return false
      return this.viewMode || !this.approveData.editable
    },
    tdClass() {
      return this.isView ? '' : 'input-td'
    },
    approvalId() {
      return this.approval.loan_approval_id
    },
    record() {
      return this.approveData.record
    },
    isProSelf() {
      return +this.relatedData.is_pro_dir === 1
    },
  },

  watch: {
    queryId: {
      handler: function () {
        this.getLoanData().then(() => {
          this.refesAttach(this.queryId, this.attachName)
        })
      },
      immediate: true,
    },
  },

  created() {},
  methods: {
    getLoanData() {
      if (!this.queryId) {
        return
      }
      this.loading = true
      return Promise.all([
        getLoanData(this.queryId),
        getContractData(this.queryId),
        getCustomerNotice(this.queryId),
      ])
        .then(([res, contrustApproval, notice]) => {
          this.approval = res
          this.contrustApproval = contrustApproval || {}
          this.noticeId = notice.loan_notice_id || ''
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleAttach(p, viewMode) {
      this.attachView = viewMode
      this.accept = p.accept
      this.attachMust = p.must
      this.attachType = p.attachName
      this.attachList = p.data
      this.attachVisible = true
    },
    handleSuccess(res) {
      this.$emit('success', res)
    },
    refesAttach() {
      getAttachment(this.queryId, this.attachName).then(res => {
        this.enumAttach = this.getAttachArray(res)
      })
    },
    getAttachArray(images) {
      const attachImages = this.attachName.map(() => [])
      for (const image of images) {
        const index = this.attachName.findIndex(name => image.attachment_type === name)
        if (index > -1) {
          attachImages[index].push(image)
        }
      }

      // @一阶段验收_20210704
      // 若合同签约选择线下，则附件资料中签约现场照片、合同附件扫描改为必传；
      // 保费缴纳凭证改为选传；
      // 增加“抵质押登记权证”（选填）与“共同承担责任函（盖章版）”（必填）

      const isOnlineSign = +this.contrustApproval.is_online_sign === 1

      return {
        1: {
          attachName: this.attachName[0],
          accept: '*',
          label: '签约现场照片',
          status: attachImages[0].length ? 1 : 0,
          statusLabel: attachImages[0].length ? '有' : '无',
          data: attachImages[0],
          must: !isOnlineSign,
        },
        2: {
          attachName: this.attachName[1],
          accept: '*',
          label: '合同附件扫描',
          status: attachImages[1].length ? 1 : 0,
          statusLabel: attachImages[1].length ? '有' : '无',
          data: attachImages[1],
          must: !isOnlineSign,
        },
        3: {
          attachName: this.attachName[2],
          accept: '*',
          label: '保费缴纳凭证',
          status: attachImages[2].length ? 1 : 0,
          statusLabel: attachImages[2].length ? '已上传' : '未上传',
          data: attachImages[2],
          must: false,
        },
        4: {
          attachName: this.attachName[3],
          accept: '*',
          label: '抵质押登记权证',
          status: attachImages[3].length ? 1 : 0,
          statusLabel: attachImages[3].length ? '已上传' : '未上传',
          data: attachImages[3],
          must: false,
        },
        5: {
          attachName: this.attachName[4],
          accept: '*',
          label: '共同承担责任函（盖章版）',
          status: attachImages[4].length ? 1 : 0,
          statusLabel: attachImages[4].length ? '已上传' : '未上传',
          data: attachImages[4],
          must: !this.isProSelf,
        },
      }
    },
    // 提交验证
    validateContract() {
      const enumValid = {
        gua_method_impl: '请输入反担保方案落实情况',
        pay_gua_fee: '请输入已缴担保费',
      }

      const keys = Object.keys(enumValid)
      for (const key of keys) {
        if (!this.approval[key]) {
          this.$message.error(enumValid[key])
          return false
        }
      }

      for (const attachIndex in this.enumAttach) {
        const attach = this.enumAttach[attachIndex]
        if (attach.must && attach.status !== 1) {
          this.$message.error(`请上传${attach.label}`)
          return false
        }
      }

      return true
    },
    submitLoanData() {},
    handlePass() {
      const valid = this.validateContract()
      if (!valid) return false
      return this.updataApproval()
      // this.$utils
      //   .msgbox({
      //     message: '是否提交？',
      //     type: 'warning',
      //     beforeClose: () =>
      //   })
      //   .then(res => {
      //     this.$message.success('提交成功')
      //     this.$emit('success', res)
      //   })
      //   .catch(() => this.$message.error(`保存失败，请重试！`))
    },
    // postApproval(status) {
    //   this.saveLoading = true
    //   return this.updataApproval()
    //     .then(() => {
    //       // this.addApproveData(status)
    //       // sendNotice(this.relatedData, this.noticeId).catch(() =>
    //       //   this.$message.error('放款通知书发放失败！！')
    //       // )
    //     })
    //     .finally(() => {
    //       this.saveLoading = false
    //     })
    // },
    updataApproval() {
      // 修改
      const data = {
        gua_method_impl: this.approval.gua_method_impl,
        pay_gua_fee: this.approval.pay_gua_fee,
        customer_related_id: this.queryId,
        add_up_reply_funds: this.entrustContract.reply_funds,
        current_reply_funds: this.entrustContract.reply_funds,
      }
      if (this.approvalId) {
        return updateLoanApproval(this.approvalId, data)
      }
      // 添加
      return addLoanApproval({
        ...data,
        res_b_person: this.relatedData.res_b_name,
        res_a_person: this.userName,
        res_a_date: this.$utils.dateFormat(new Date(), 'yyyy-MM-dd hh:mm:ss'),
        service_id: this.relatedData.service_id,
        recommend_service: this.relatedData.recommend_service,
      })
    },
    handleReject() {
      this.$utils
        .msgbox({
          message: '确认放款审批拒绝？',
          type: 'danger',
          beforeClose: () => this.postApproval(2),
        })
        .then(res => {
          this.$message.success('操作成功')
          this.$emit('success', res)
        })
        .catch(() => this.$message.error(`操作失败，请重试！`))
    },
    addApproveData(status) {
      const { process } = this.approveData
      const { id, task_id: taskId } = this.record.find(it => it.editable) || {}

      const data = {
        opinion: '',
        status,
        process,
        taskId,
      }

      return id ? updateApprove(id, data, this.user) : addApprove(this.queryId, data, this.user)
    },
  },
}
</script>
<style lang="scss" scoped>
@import './index.scss';
.flex-2 {
  flex: 2;
}
</style>
